﻿/*
   Open Intel 
   Copyright © 2011 – ISC. All Rights Reserved.
*/

using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using Caliburn.Micro;
using OI.Async;
using OI.DataModel;
using OI.Framework;

namespace OI.ViewModels
{
    [Export(typeof(AppsViewModel))]
    [PartCreationPolicy(CreationPolicy.Shared)]
    public class AppsViewModel : Screen
    {
        public BindableCollection<OIApp> Items { get; set; }

        // when this view loads, async populate apps
        protected override void OnViewLoaded(object view)
        {
             Coroutine.BeginExecute(LoadApps());
        }


        public IEnumerator<IResult> LoadApps()
        {
            IoC.Get<IShell>().Busy(true, "loading apps...");

            var sq = new CatalogQuery<OIApp>(Configuration.Jurisdiction.ID);
            yield return sq;

            // filter by "source filter"
            var dstResults = sq.Results;


            // if no URI to thumbnail provided, use default
            dstResults.Apply((r) =>
            {
                if (string.IsNullOrEmpty(r.ThumbnailURI))
                {
                    r.ThumbnailURI = Configuration.DefaultThumbnailPath + Configuration.DefaultThumbnailFile;
                }
                else if (r.ThumbnailURI.IndexOf("/") == -1)
                {
                    r.ThumbnailURI = Configuration.DefaultThumbnailPath + r.ThumbnailURI.Trim('/');
                }
            });

            Items = new BindableCollection<OIApp>(dstResults);
            NotifyOfPropertyChange(() => Items);

            IoC.Get<IShell>().Busy(false);
        }


        public void Select(OIApp item)
        {
            string startPage = null;

            if (string.IsNullOrEmpty(item.UriOverride))
            {
                startPage = Configuration.GetBaseURI() +
                    Configuration.StartPage +
                    "?" +
                    Configuration.QueryStringJurisdictionID +
                    "=" +
                    Configuration.Jurisdiction.JurisdictionID +
                    "&" +
                    Configuration.QueryStringShareID +
                    "=" +
                    item.ShareID;
            }
            else
            {
                startPage = item.UriOverride;
            }

            System.Windows.Browser.HtmlPage.Window.Navigate(new Uri(startPage));
        }
    }
}
